#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AI API接口 - 提供智能法律服务
"""

from flask_restful import Resource, reqparse
from flask import request, current_app, g
import logging

from app.services.ai_service import ai_service
from app.services.civil_code_service import civil_code_service
from app.utils.response_utils import create_response
from app.middleware.ip_middleware import get_current_user_id, get_current_user_ip

logger = logging.getLogger(__name__)

class ArticleExplanationAPI(Resource):
    """条文解读API"""
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('article_content', type=str, required=True, help='条文内容不能为空')

    def post(self):
        try:
            args = self.parser.parse_args()
            explanation = ai_service.explain_article(args['article_content'])
            return create_response(success=True, data={'explanation': explanation})
        except Exception as e:
            current_app.logger.error(f"条文解读失败: {e}")
            return create_response(success=False, error={"code": "EXPLANATION_FAILED", "message": str(e)}, status_code=500)

class LegalQuestionAPI(Resource):
    """法律问答API"""
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('question', type=str, required=True, help='问题不能为空')

    def post(self):
        try:
            args = self.parser.parse_args()
            answer = ai_service.answer_legal_question(args['question'])
            return create_response(success=True, data={'answer': answer})
        except Exception as e:
            current_app.logger.error(f"法律问答失败: {e}")
            return create_response(success=False, error={"code": "QNA_FAILED", "message": str(e)}, status_code=500)

class AISearchSuggestionsAPI(Resource):
    """智能搜索建议API"""
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('query', type=str, required=True, help='搜索词不能为空', location='args')
    
    def get(self):
        try:
            args = self.parser.parse_args()
            suggestions = ai_service.get_search_suggestions(args['query'])
            return create_response(success=True, data={'suggestions': suggestions})
        except Exception as e:
            current_app.logger.error(f"获取智能搜索建议失败: {e}")
            return create_response(success=False, error={"code": "SUGGESTIONS_FAILED", "message": str(e)}, status_code=500)

class LegalScenarioAPI(Resource):
    """法律场景分析API"""
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('scenario', type=str, required=True, help='场景描述不能为空')

    def post(self):
        try:
            args = self.parser.parse_args()
            result = ai_service.analyze_legal_scenario(args['scenario'])
            
            # result可能包含'analysis'或'feedback'
            if 'analysis' in result:
                return create_response(success=True, data={'analysis': result['analysis']})
            elif 'feedback' in result:
                return create_response(success=True, data={'feedback': result['feedback']})
            else:
                # 作为降级措施，处理预料之外的返回结构
                current_app.logger.warning(f"AI服务返回未知结构: {result}")
                return create_response(success=False, error={"code": "UNKNOWN_AI_RESPONSE", "message": "AI服务返回了未知的数据结构"}, status_code=500)

        except Exception as e:
            current_app.logger.error(f"法律场景分析失败: {e}", exc_info=True)
            return create_response(success=False, error={"code": "SCENARIO_ANALYSIS_FAILED", "message": str(e)}, status_code=500)

class AIHealthAPI(Resource):
    """AI服务健康检查API"""
    
    def get(self):
        """获取AI服务状态"""
        try:
            status = ai_service.get_service_status()
            
            return create_response(
                success=status['status'] == 'healthy',
                data=status,
                message=f"AI服务状态: {status['status']}"
            )
                
        except Exception as e:
            current_app.logger.error(f"AI健康检查失败: {e}")
            return create_response(success=False, error={"code": "AI_HEALTH_CHECK_FAILED", "message": str(e)}, status_code=500)
